#include "protocol.h"
#include "uart.h"
#include "bl602StateHandle.h"

static uint8_t ackFlag = 0;

void bl602DataHandle(uint8_t cmd, uint8_t *data)
{
    switch (cmd)
    {
    case 0:
    {
        ackFlag = 1;
    }
    break;
    case 1:
    {
        uint16_t min = data[0] | (data[1] << 8);
        uint16_t max = data[2] | (data[3] << 8);
        uint8_t rec[2] = {0, cmd};
        setHeight(min, max);

        receiveData(0, 2, rec);
    }
    break;
    case 2:
    {
        int16_t min = data[0] | (data[1] << 8);
        int16_t max = data[2] | (data[3] << 8);
        uint8_t rec[2] = {0, cmd};
        setAcc(min, max);

        receiveData(0, 2, rec);
    }
    break;
    case 3:
    {
        int16_t acc = getAccAvg();
        uint8_t rec[2] = {acc, acc >> 8};
        receiveData(cmd, 2, rec);
        // 每次获取后刷新均值
        resetAvg();
    }
    break;
    case 4:
    {
        uint8_t time = data[0];
        uint8_t rec[2] = {0, cmd};
        if (time < 1)
        {
            time = 1;
        }
        receiveData(0, 2, rec);
    }
    break;
    case 5:
    {
        uint16_t h = getHeight();
        uint8_t rec[2] = {h, h >> 8};
        receiveData(cmd, 2, rec);
    }
    break;
    default:
        break;
    }
}

void receiveData(uint8_t cmd, uint8_t len, uint8_t *data)
{
    uint8_t rec[16] = {0xFB, 0xFB, len, cmd};
    uint8_t i;
    uint8_t sum = len + cmd;
    for (i = 0; i < len; i++)
    {
        rec[4 + i] = data[i];
        sum += data[i];
    }
    rec[4 + i] = sum;
    uartSendData(rec, len + 5);
}
